<template>
	<view class="collect-page">
		<!-- 导航栏 -->
		<view class="nav-bar">
			<text class="nav-title">我的收藏</text>
			<text class="edit-btn" @click="toggleEditMode">{{ editMode ? '取消' : '编辑' }}</text>
		</view>

		<!-- 收藏列表 -->
		<view class="collect-list" v-if="collectList.length > 0">
			<view class="collect-item" v-for="(goods, index) in collectList" :key="goods.id"
				:class="{ 'edit-active': editMode }">
				<view v-if="editMode" class="checkbox-wrapper" @click="toggleSelect(index)">
					<view class="checkbox" :class="{ 'checked': goods.selected }"></view>
				</view>
				<view class="goods-image" @click="navigateToDetail(goods.id)">
					<image :src="goods.thumb" mode="aspectFill"></image>
				</view>
				<view class="goods-info" @click="navigateToDetail(goods.id)">
					<text class="goods-name">{{goods.goods_name}}</text>
					<text class="goods-desc">{{goods.description}}</text>
					<text class="goods-price">{{goods.sell_price}}元/{{goods.company}}</text>
					<text class="goods-stock">库存: {{goods.num}}</text>
				</view>
				<button class="add-cart-btn" type="primary" size="mini"
					@click.stop="showSpecModal(goods)">加入购物车</button>
			</view>
		</view>
		<view class="empty-state" v-if="collectList.length === 0 && !loading">
			<image src="/static/androidImg/icon_not_data.png" class="empty-img"></image>
			<text class="empty-text">暂无收藏商品</text>
		</view>

		<!-- 编辑模式底部操作栏 -->
		<view class="batch-delete" v-if="editMode">
			<view class="checkbox-wrapper" @click="toggleAllSelect">
				<view class="checkbox" :class="{ 'checked': selectAll }"></view>
				<text class="all-select-text">全选</text>
				<text class="selected-count" v-if="selectedIds.length > 0">已选择 ({{ selectedIds.length }})</text>
			</view>
			<view>
				<button class="delete-btn" @click="confirmDelete" :disabled="selectedIds.length < 0">
					取消收藏
				</button>
			</view>
		</view>

		<!-- 规格选择弹窗组件 -->
		<spec-modal v-if="currentGoods" :goods="currentGoods" :show.sync="specModalShow"
			@confirm="handleSpecConfirm"></spec-modal>
	</view>
</template>

<script>
	import {
		getUserCollect,
		delUserCollect
	} from '../../api/request.js';
	import specModal from '../../components/specModal.vue';
	export default {
		components: {
			specModal
		},
		data() {
			return {
				collectList: [],
				page: 1,
				hasMore: true,
				loading: false,
				editMode: false,
				selectedIds: [],
				selectAll: false,
				currentGoods: null,
				specModalShow: false
			};
		},

		onLoad() {
			// 加载第一页收藏数据
			this.loadCollectData();
		},

		methods: {
			// 切换全选
			toggleAllSelect() {
				console.log('eeeeeeeeeeeeeee', this.isAllSelected)
				this.selectAll = !this.selectAll;
				this.collectList.forEach(item => {
					item.selected = this.selectAll;
				});
				this.calculateTotal();
			},
			// 切换单个商品选择状态
			toggleSelect(index) {
				console.log('aaaaaaaaaaaa', this.collectList[index].selected)
				this.collectList[index].selected = !this.collectList[index].selected;
				// 检查是否全选
				this.selectAll = this.collectList.every(item => item.selected);
				this.calculateTotal();
			},
			// 计算总价和选中数量
			calculateTotal() {
				let count = 0;
				this.collectList.forEach(item => {
					if (item.selected) {
						count++;
					}
				});
				this.selectedCount = count;
				// 更新选中ID数组
				this.selectedIds = this.collectList.filter(item => item.selected).map(item => item.id);
			},
			// 加载收藏数据
			loadCollectData() {
				if (this.loading || !this.hasMore) return;

				this.loading = true;
				getUserCollect({
						page: this.page
					})
					.then(res => {
						if (res.code === 1 && res.data && res.data.rows) {
							const newData = res.data.rows.map(item => ({
								...item,
								selected: false
							}));
							if (this.page === 1) {
								this.collectList = newData;
							} else {
								this.collectList = [...this.collectList, ...newData];
							}

							// 判断是否有更多数据
							this.hasMore = newData.length >= 10; // 假设每页10条
						} else {
							this.hasMore = false;
						}
					})
					.catch(err => {
						console.error('获取收藏列表失败:', err);
					})
					.finally(() => {
						this.loading = false;
					});
			},

			// 加载更多
			onReachBottom() {
				if (!this.hasMore || this.loading) return;
				this.page++;
				this.loadCollectData();
			},

			// 切换编辑模式
			toggleEditMode() {
				this.editMode = !this.editMode;
				// 退出编辑模式时清空选择
				if (!this.editMode) {
					this.selectedIds = [];
					this.selectAll = false;
				}
			},

			// 全选/取消全选
			toggleSelectAll(e) {
				// 检查是否有事件对象和正确的事件结构
				let isChecked;
				if (e && e.detail && e.detail.value !== undefined) {
					// 尝试从事件对象中获取值
					isChecked = e.detail.value;
				} else {
					// 如果事件对象不完整，使用selectAll的当前值的相反值
					isChecked = !this.selectAll;
				}

				if (isChecked) {
					// 全选
					this.selectedIds = this.collectList.map(item => item.id);
				} else {
					// 取消全选
					this.selectedIds = [];
				}
				// 注意：不需要手动设置this.selectAll，因为watch会根据selectedIds的变化自动更新它
			},

			// 确认删除所选收藏
			confirmDelete() {
				if (this.selectedIds.length === 0) return;

				uni.showModal({
					title: '提示',
					content: `确定要取消收藏这${this.selectedIds.length}项吗？`,
					success: (res) => {
						if (res.confirm) {
							this.deleteSelectedCollect();
						}
					}
				});
			},

			// 删除所选收藏
			deleteSelectedCollect() {
				const id = this.selectedIds.join(',');
				this.loading = true;
				delUserCollect({
						id
					})
					.then(res => {
						if (res.code === 1) {
							uni.showToast({
								title: '取消收藏成功',
								icon: 'success'
							});

							// 从列表中移除已删除的项
							this.collectList = this.collectList.filter(item => !this.selectedIds.includes(item.id));
							this.selectedIds = [];
							this.selectAll = false;
						} else {
							uni.showToast({
								title: res.msg || '取消收藏失败',
								icon: 'none'
							});
						}
					})
					.catch(err => {
						console.error('取消收藏失败:', err);
						uni.showToast({
							title: err.msg || '网络错误，取消收藏失败',
							icon: 'none'
						});
					})
					.finally(() => {
						this.loading = false;
					});
			},
			// 显示规格选择弹窗
			showSpecModal(goods) {
				this.currentGoods = goods;
				this.specModalShow = true;
			},

			// 跳转到商品详情页
			navigateToDetail(goodsId) {
				if (this.editMode) return;
				uni.navigateTo({
					url: `/pages/goods/detail?goods_id=${goodsId}`
				})
			},

			// 处理规格确认
			handleSpecConfirm(data) {
				const {
					goods_id,
					num,
					item
				} = data;

				// 添加到购物车的逻辑
				uni.showToast({
					title: '添加购物车成功',
					icon: 'success'
				});
			}
		},

		watch: {
			// 监听选择变化，更新全选状态
			selectedIds: {
				handler() {
					this.selectAll = this.collectList.length > 0 && this.selectedIds.length === this.collectList.length;
				},
				deep: true
			}
		}
	};
</script>

<style lang="scss">
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 200rpx;

		.empty-img {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 30rpx;
			opacity: 0.6;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	.checkbox-wrapper {
		display: flex;
		align-items: center;

		.checkbox {
			width: 32rpx;
			height: 32rpx;
			border: 2rpx solid #999;
			border-radius: 50%;
			margin-right: 10rpx;

			&.checked {
				border-color: #ff6b00;
				background-color: #ff6b00;
				position: relative;

				&::after {
					content: '';
					position: absolute;
					left: 6rpx;
					top: 10rpx;
					width: 12rpx;
					height: 6rpx;
					border-left: 2rpx solid #fff;
					border-bottom: 2rpx solid #fff;
					transform: rotate(-45deg);
				}
			}
		}

		.all-select-text {
			font-size: 28rpx;
			color: #333;
		}
	}

	.collect-page {
		min-height: 100vh;
		background-color: #f5f5f5;

		.nav-bar {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;

			.nav-title {
				font-size: 36rpx;
				font-weight: bold;
			}

			.edit-btn {
				font-size: 32rpx;
				color: #ff6b6b;
			}
		}

		.collect-list {
			display: flex;
			flex-direction: column;
			gap: 10px;
			padding: 10px 0;
			min-height: calc(100vh - 100rpx);

			.collect-item {
				transition: transform 0.3s ease;
				display: flex;
				margin-bottom: 10px;
				background-color: #fff;
				border-radius: 8px;
				overflow: hidden;
				position: relative;
				padding: 10px;
				box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);

				.goods-image {
					width: 120px;
					height: 120px;
					margin-right: 10px;
					flex-shrink: 0;
				}

				.goods-image image {
					width: 100%;
					height: 100%;
				}

				.goods-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
				}

				.goods-name {
					font-size: 14px;
					color: #333;
					margin-bottom: 5px;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 1;
					overflow: hidden;
				}

				.goods-price {
					font-size: 16px;
					color: #e63946;
					font-weight: bold;
				}

				.goods-stock {
					font-size: 12px;
					color: #999;
				}

				.goods-desc {
					font-size: 14px;
					color: #999;
				}

				.add-cart-btn {
					position: absolute;
					bottom: 20rpx;
					right: 20rpx;
					background-color: #FE0000;
					color: #fff;
					font-size: 24rpx;
					padding: 0 20rpx;
					height: 50rpx;
					line-height: 50rpx;
					border-radius: 25rpx;
					z-index: 10;
				}

				.collect-item.edit-active {
					transform: translateX(40px);
				}
			}



			.loading-state,
			.no-more {
				text-align: center;
				padding: 30rpx;
				font-size: 28rpx;
				color: #999;
			}
		}

		.batch-delete {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 30rpx;
			background-color: #fff;
			border-top: 1rpx solid #eee;

			.select-all {
				display: flex;
				align-items: center;
				margin-right: 20rpx;

				.select-all-text {
					font-size: 32rpx;
					color: #333;
					margin-left: 10rpx;
				}
			}

			.selected-count {
				font-size: 32rpx;
				color: #ff6b6b;
				margin-left: 10rpx;
			}

			.delete-btn {
				background-color: #FE0000;
				color: #fff;
				border: none;
				padding: 15rpx 40rpx;
				border-radius: 50rpx;
				font-size: 32rpx;

				&[disabled] {
					background-color: #ccc;
				}
			}
		}
	}
</style>